/*
 * @Author: WangLi
 * @Date: 2021-07-04 22:23:26
 * @LastEditors: WangLi
 * @LastEditTime: 2024-03-19 05:53:23
 * @Description:
 */
import request from "@shene/wx-request";
import baseConfig from "../core/config";
import { createSign } from "../utils/sign";
import { getUser } from "../utils/storage";

const { baseUrl, appkey, secretKey, loadingTime } = baseConfig;

// 请求异常提示信息
const codeMessage = {
  400: "发出的请求有错误，服务器没有进行新建或修改数据的操作。",
  401: "用户没有权限（令牌、用户名、密码错误）。",
  403: "用户得到授权，但是访问是被禁止的。",
  404: "发出的请求针对的是不存在的记录，服务器没有进行操作。",
  406: "请求的格式不可得。",
  410: "请求的资源被永久删除，且不会再得到的。",
  412: "客户端请求信息的先决条件错误。",
  422: "当创建一个对象时，发生一个验证错误。",
  500: "请您稍后再试一次",
  502: "网关错误。",
  503: "服务不可用，服务器暂时过载或维护。",
  504: "网关超时。",
};

const tokenErrorCodes = ["100000", "100001", "100002", "100003", "100004"];
//生成通用请求头部信息
const genRequestHeader = () => {
  const userInfo = getUser();
  if (userInfo) {
    return {
      authorization: userInfo.token,
      "Content-Type": "application/json",
    };
  }
  return createSign(appkey, secretKey);
};

// 异常处理程序
const errorHandler = async (error) => {
  const { response = {} } = error;
  const { data = {} } = response;
  const errortext = data.error || data.msg || codeMessage[response.statusCode];
  wx.showToast({
    title: errortext || codeMessage["500"],
    icon: "none",
    duration: 2000,
  });
  return Promise.reject(data);
};

let instance = request.create({
  baseURL: baseUrl,
  timeout: 1000 * 30,
});

// 请求拦截
instance.interceptors.request.use((config) => {
  config.header = {
    ...config.header,
    ...genRequestHeader(),
  };
  return config;
}, errorHandler);

// 响应拦截
instance.interceptors.response.use(async (response) => {
  let { data } = response;
  if (data.code !== "0") {
    wx.showToast({
      title: data.msg || codeMessage["500"],
      icon: "none",
      duration: loadingTime,
    });
  }
  if (tokenErrorCodes.includes(data.code)) {
    wx.redirectTo({
      url: "/pages/login/index",
    });
  }
  return data;
}, errorHandler);

export default instance;
